<template>
  <div class="scholarship-container">
    <div class="header">
      <div class="left">
        <h2>奖学金管理</h2>
      </div>
      <div class="right">
        <!-- 搜索框 -->
        <el-input
          v-model="searchQuery"
          placeholder="搜索奖学金名称"
          style="width: 220px"
          clearable
          @clear="handleSearch"
          @keyup.enter="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <!-- 添加按钮 -->
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          添加奖学金
        </el-button>
      </div>
    </div>

    <el-card class="table-card">
      <el-table
        v-loading="loading"
        :data="scholarships"
        border
        stripe
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="title" label="项目名称" min-width="150" />
        <el-table-column prop="amount" label="金额" width="120">
          <template #default="{ row }">
            ¥{{ row.amount }}
          </template>
        </el-table-column>
        <el-table-column prop="quota" label="名额" width="100" />
        <el-table-column label="申请时间" width="300">
          <template #default="{ row }">
            {{ formatDate(row.startTime) }} 至 {{ formatDate(row.endTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" min-width="200" show-overflow-tooltip />
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50]"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      :title="dialogType === 'add' ? '添加奖学金' : '编辑奖学金'"
      v-model="dialogVisible"
      width="600px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="项目名称" prop="title">
          <el-input v-model="form.title" placeholder="请输入项目名称" />
        </el-form-item>
        <el-form-item label="金额" prop="amount">
          <el-input-number 
            v-model="form.amount"
            :min="0"
            :precision="2"
            :step="100"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="名额" prop="quota">
          <el-input-number
            v-model="form.quota"
            :min="1"
            :precision="0"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="申请时间" prop="timeRange">
          <el-date-picker
            v-model="form.timeRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            :default-time="[
              new Date(2000, 1, 1, 0, 0, 0),
              new Date(2000, 1, 1, 23, 59, 59)
            ]"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="4"
            placeholder="请输入项目描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button
          type="primary"
          :loading="submitting"
          @click="handleSubmit"
        >
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'TeacherScholarshipList'
}
</script>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus } from '@element-plus/icons-vue'
import { getScholarships, createScholarship, updateScholarship, deleteScholarship } from '@/api/teacher/scholarship'
import { formatDate } from '@/utils/format'

// 表格数据
const loading = ref(false)
const scholarships = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const searchQuery = ref('')

// 获取奖学金列表
const fetchScholarships = async () => {
  try {
    loading.value = true
    const response = await getScholarships({
      page: currentPage.value - 1,
      size: pageSize.value,
      keyword: searchQuery.value
    })
    
    if (response) {
      scholarships.value = response.content
      total.value = response.totalElements
    }
  } catch (error) {
    console.error('Failed to fetch scholarships:', error)
    ElMessage.error('获取奖学金列表失败')
  } finally {
    loading.value = false
  }
}

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchScholarships()
}

// 处理分页
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchScholarships()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchScholarships()
}

// 表单相关
const dialogVisible = ref(false)
const dialogType = ref('add')
const formRef = ref(null)
const submitting = ref(false)
const currentId = ref(null)

const form = ref({
  title: '',
  amount: 0,
  quota: 1,
  timeRange: [],
  description: ''
})

const rules = {
  title: [
    { required: true, message: '请输入项目名称', trigger: 'blur' }
  ],
  amount: [
    { required: true, message: '请输入金额', trigger: 'blur' }
  ],
  quota: [
    { required: true, message: '请输入名额', trigger: 'blur' }
  ],
  timeRange: [
    { required: true, message: '请选择申请时间', trigger: 'change' }
  ],
  description: [
    { required: true, message: '请输入项目描述', trigger: 'blur' }
  ]
}

const resetForm = () => {
  form.value = {
    title: '',
    amount: 0,
    quota: 1,
    timeRange: [],
    description: ''
  }
}

const handleAdd = () => {
  dialogType.value = 'add'
  resetForm()
  dialogVisible.value = true
}

const handleEdit = (row) => {
  dialogType.value = 'edit'
  currentId.value = row.id
  form.value = {
    title: row.title,
    amount: row.amount,
    quota: row.quota,
    timeRange: [row.startTime, row.endTime],
    description: row.description
  }
  dialogVisible.value = true
}

const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除该奖学金项目吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteScholarship(row.id)
      ElMessage.success('删除成功')
      fetchScholarships()
    } catch (error) {
      console.error('Delete failed:', error)
      ElMessage.error(error.response?.data || '删除失败')
    }
  })
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    submitting.value = true
    
    const [startTime, endTime] = form.value.timeRange
    const data = {
      ...form.value,
      startTime: startTime ? new Date(startTime).toISOString().slice(0, 19) : null,
      endTime: endTime ? new Date(endTime).toISOString().slice(0, 19) : null
    }
    delete data.timeRange
    
    console.log('Submitting data:', data)  // 添加日志
    
    if (dialogType.value === 'add') {
      await createScholarship(data)
      ElMessage.success('添加成功')
    } else {
      await updateScholarship(currentId.value, data)
      ElMessage.success('更新成功')
    }
    
    dialogVisible.value = false
    fetchScholarships()
  } catch (error) {
    console.error('Submit failed:', error)
    // 显示更详细的错误信息
    const errorMessage = error.response?.data?.message || 
                        error.response?.data || 
                        error.message || 
                        '提交失败'
    ElMessage.error(errorMessage)
  } finally {
    submitting.value = false
  }
}

// 在组件挂载时获取数据
onMounted(() => {
  fetchScholarships()
})
</script>

<style scoped>
.scholarship-container {
  padding: 20px;
}

.header {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #fff;
  padding: 16px 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.left {
  display: flex;
  align-items: center;
  gap: 16px;

  h2 {
    margin: 0;
    font-size: 18px;
    font-weight: 600;
    color: #303133;
  }
}

.right {
  display: flex;
  align-items: center;
  gap: 12px;
}

.table-card {
  margin-bottom: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.pagination {
  margin-top: 20px;
  padding: 16px 20px;
  display: flex;
  justify-content: flex-end;
  background-color: #fff;
  border-top: 1px solid #ebeef5;
}

/* 调整表格内容垂直对齐 */
:deep(.el-table .cell) {
  display: flex;
  align-items: center;
}

/* 优化按钮样式 */
:deep(.el-button--small) {
  padding: 8px 16px;
}
</style> 